package com.newblog2_0.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.newblog2_0.common.AppVarible;
import com.newblog2_0.common.ResultAjax;
import com.newblog2_0.common.SessionUtils;
import com.newblog2_0.mapper.UserMapper;
import com.newblog2_0.model.ImageUtil;
import com.newblog2_0.model.UserInfo;
import com.newblog2_0.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * Created with Intellij IDEA.
 * Description;
 * User:TQ02
 * Data:2023-12-16
 * Time:15:17
 * Text：
 */
@RestController
@RequestMapping("/user")
public class UserController {


    @Autowired
    private UserService userService;
    @Autowired
    UserMapper mapper;

     @Autowired
     ImageUtil imageUtil;

    //注册
    @PostMapping("/reg")
    public ResultAjax reg(UserInfo user) {
        UserInfo u1 = mapper.selectOne(new QueryWrapper<UserInfo>().eq("uName", user.getUName()));
        if (user == null || !StringUtils.hasLength(user.getUName())
                || !StringUtils.hasLength(user.getPassword()) || u1 != null)
            return ResultAjax.fail(1, "非法");
        if (userService.save(user)) {
            return ResultAjax.succ("注册成功");
        }
        return ResultAjax.fail(1, "非法");
    }
    //验证码图片
    @RequestMapping("/generateImage")
    public void generateImage(HttpServletRequest req, HttpServletResponse res){
        imageUtil.init();
        //验证码文字
        final String verifyCode=imageUtil.getStr();
        //验证码图片
        final ByteArrayInputStream image=imageUtil.getImage();
        res.setContentType("image/jpeg");
        //将文章存储在session当中
        HttpSession session= req.getSession();
        session.setAttribute(AppVarible.SESSION_USERINFO_KEY,verifyCode);

        byte[] bytes=new byte[1024];
        try(final ServletOutputStream out=res.getOutputStream()){
            while(image.read(bytes)!=-1){
                out.write(bytes);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //登陆
    @PostMapping("/login")
    public ResultAjax login(UserInfo user, HttpServletRequest req,String password2) {
        if (user == null || !StringUtils.hasLength(user.getUName())
                || !StringUtils.hasLength(user.getPassword()))
            return ResultAjax.fail(-1, "非法");

        UserInfo u1 = mapper.selectOne(new QueryWrapper<UserInfo>().eq("uName", user.getUName()));
        if (u1 == null || u1.getUId() == 0 || !user.getPassword().equals(u1.getPassword())) {
            return ResultAjax.fail(2, "账号或密码错误");
        }
        if(!password2.equals(req.getSession().getAttribute("SESSION_USERINFO").toString())){
            return ResultAjax.fail(2, "验证码错误");
        }
        HttpSession session = req.getSession();
        session.setAttribute(AppVarible.SESSION_USERINFO_KEY, u1);
        return ResultAjax.fail(200, "登陆成功");
    }

    //    退出
    @PostMapping("logout")
    public ResultAjax logout(HttpServletRequest req) {
        HttpSession session = req.getSession(false);
        if (session != null && session.getAttribute(AppVarible.SESSION_USERINFO_KEY) != null) {
            session.removeAttribute(AppVarible.SESSION_USERINFO_KEY);
        }
        return ResultAjax.succ(1);
    }

    //    修改密码
    @PostMapping("/changePassword")
    public ResultAjax changePassword(String password1, String password2, String password3, HttpServletRequest req) {
        UserInfo user = SessionUtils.getUser(req);
        if (user == null) {
            return ResultAjax.fail(-1, "请先登陆");
        }
        //验证密码
        String name = user.getPassword();
        if (!user.getPassword().equals(password1) && !password2.equals(password3)) {
            return ResultAjax.fail(-1, "密码错误");
        }
        int num = userService.changepd(user.getUName(), password2);
        user.setPassword(password2);
        HttpSession session = req.getSession();
        session.setAttribute(AppVarible.SESSION_USERINFO_KEY, user);
        return ResultAjax.succ(200, "修改成功");

    }

    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile multipartfile, HttpServletRequest request) {

        UserInfo user =SessionUtils.getUser(request);


        String relativePath = System.getProperty("user.dir") + "\\img";
        //String currentWorkingDir = System.getProperty("user.dir"); // 获取当前工作目录的路径
        String fullPath =  relativePath; // 拼接成完整的路径

        File folder = new File(fullPath); // 创建File对象

        if (!folder.isDirectory()) {
            folder.mkdirs();
        }
        //获取文件名
        String oldname = multipartfile.getOriginalFilename();
        String newname =oldname;
        int num=userService.changeph("img/"+newname, user.getUName());

        try {
            File newFile = new File(folder, newname);
            multipartfile.transferTo(newFile);
            System.out.println(new File(folder, newname).getAbsolutePath());//输出（上传文件）保存的相对路径
            String filePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/update/"+ newname;
            return filePath + "上传成功";
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传失败!";
    }



}
